﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Automation;
using System.Runtime.InteropServices;

namespace IEIDEWindowsManagement
{
    public class AxWindowsHelper
    {
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

        ArrayList aotWindows;

        public AxWindowsHelper()
        {
        }

        private void findAOTWindows(long mdiHandle)
        {
            aotWindows = new ArrayList();

            IntPtr mdiHandlePointer = new IntPtr(mdiHandle);

            for (IntPtr childHandlePointer = FindWindowEx(mdiHandlePointer, IntPtr.Zero, null, null); childHandlePointer != IntPtr.Zero; childHandlePointer = FindWindowEx(mdiHandlePointer, childHandlePointer, null, null))
            {
                IntPtr childPaneWndPointer = FindWindowEx(childHandlePointer, IntPtr.Zero, "AxPaneWnd", null);

                if (childPaneWndPointer != IntPtr.Zero)
                {
                    AutomationElement childPaneElement = AutomationElement.FromHandle(childPaneWndPointer);

                    if (childPaneElement != null &&
                        childPaneElement.Current.Name == "AOT")
                    {
                        aotWindows.Add(childHandlePointer.ToInt32());
                    }
                }
            }
        }

        public string getAOTWindows(long mdiHandle)
        {
            string ret = "";

            this.findAOTWindows(mdiHandle);

            foreach (int handle in aotWindows)
            {
                ret += handle.ToString() + "|";
            }

            return ret;
        }
    }
}
